<?php

namespace App\Model;

use App\Job\PushOrder;
use App\Services\AdapayService;
use App\Services\Iot\IotService1 as IotService;
use Carbon\Carbon;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Context\ApplicationContext;
use Hyperf\Database\Model\Relations\BelongsTo;
use Hyperf\Utils\Arr;
use Util\Common;

/**
 * App\Order
 *
 * @property int $id
 * @property int $device_id 设备编号
 * @property string $number 订单号
 * @property string $sn 设备编号
 * @property string $payment_type 订单类型
 * @property int $channel_number 通道号
 * @property int $station_id 站点id
 * @property int $user_id 用户
 * @property \Carbon\Carbon|null $estimate_stop_at 预选停止时间
 * @property int|null $duration_seconds 使用时长 秒
 * @property int|null $platform_profit 平台收益
 * @property \Carbon\Carbon|null $stop_at 停止时间
 * @property string|null $stop_reason 停止原因
 * @property string $status 状态
 * @property string|null $result 结果
 * @property-read \App\Model\Device $device
 * @property-read \App\Model\Feedback $feedback
 * @property-read \App\Model\Station $station
 * @property-read \App\Model\User $user
 * @property-read \App\Model\CouponRecord $couponRecord
 */
class OrderHistory extends Model
{

    public bool $timestamps = true;
    protected ?string $table = 'orders_history';


    public static array $paymentTypeMap = [
        Bill::PAYMENT_TYPE_WE_CHAT_PAY => '微信支付',
        Bill::PAYMENT_TYPE_ALI_PAY => '支付宝支付',
        Bill::PAYMENT_TYPE_BALANCE => '余额',
        Bill::PAYMENT_TYPE_IC_CARD => '刷卡',
    ];

    protected array $casts = [
        'estimate_stop_at' => 'datetime',
        'stop_at' => 'datetime',
        'extra' => 'json',
    ];
//    protected array $fillable = [
//        'device_id', 'number', 'sn', 'user_id', 'payment_type',
//        'channel_number', 'station_id', 'fee', 'minutes',
//        'estimate_stop_at', 'estimate_minutes', 'platform_profit',
//        'stop_at', 'return_fee', 'is_return_fee', 'duration_seconds',
//        'stop_reason', 'status', 'extra', 'electric_quantity', 'power',
//        'coupon_record_id', 'original_fee', 'surplus_electricity',
//        'is_fail', 'service_id', 'service_fee', 'power_fee', 'is_draw', 'charge_service',
//        'is_autoload', 'charge_id', 'charge_detail_id', 'out_ord_id', 'use_elec', 'use_fee',
//        'pay_at', 'refund_at', 'payment_id', 'is_check', 'distributor_id', 'is_disabled'
//    ];
    protected array $guarded = [];

    const FREE_SECONDS = 420;

//    //最长充电时长
//    const MAX_HOURS = 8;

    const RETURN = 1;
    const UNRETURN = 0;

    const STATUS_UNPAID = 'unpaid';
    const STATUS_PAID = 'paid';
    const STATUS_USING = 'using';
    const STATUS_END = 'end';
    const STATUS_FAILED = 'failed';
    const STATUS_REFUNDED = 'refunded';
    const STATUS_PAY_TIMEOUT = 'timeout';

    const STATUS_MAP = [
        self::STATUS_UNPAID => '未支付',
        self::STATUS_PAID => '已支付',
        self::STATUS_USING => '使用中',
        self::STATUS_END => '已完成',
        self::STATUS_FAILED => '失败',
        self::STATUS_REFUNDED => '已退款',
        self::STATUS_PAY_TIMEOUT => '支付超时'
    ];

    //关联的账单类型
    const RELATE_BILL_TYPE_MAP = [
        Bill::TYPE_ORDER_PAY,
        Bill::TYPE_DISTRIBUTOR_ORDER_PROFIT,
        Bill::TYPE_DISTRIBUTOR_DIRECT_ORDER_PROFIT,
        Bill::TYPE_PLATFORM_PROFIT,
    ];

    const SUCCESS_REFUND = 1;
    const NORMAL_REFUND = 0;

    public function feedback()
    {
        return $this->hasOne(Feedback::class);
    }

    public function charge(): BelongsTo
    {
        return $this->belongsTo(ChargeOption::class, 'charge_id', 'id');
    }

    public function station(): BelongsTo
    {
        return $this->belongsTo(Station::class, 'station_id', 'id');
    }

    public function chargeDetail(): BelongsTo
    {
        return $this->belongsTo(ChargeDetail::class, 'charge_detail_id', 'id');
    }

    public function device(): BelongsTo
    {
        return $this->belongsTo(Device::class, 'device_id', 'id');
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(Distributors::class, 'distributor_id', 'id');
    }


    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function couponRecord(): BelongsTo
    {
        return $this->belongsTo(CouponRecord::class, 'coupon_record_id', 'id');
    }


    //
    public function getDurationSeconds()
    {
        //使用中的为空
        if ($this->status != self::STATUS_USING && $this->status != self::STATUS_PAID) {
            return $this->duration_seconds ?? 0;
        }

        return Carbon::now()->timestamp - $this->created_at->timestamp;
    }

    public function getNormalTime(int $power, int $chargeOptionId)
    {
        $chargeDetail = ChargeDetail::where('charge_option_id', $chargeOptionId)
            ->where('type', ChargeDetail::POWER_TYPE)
            ->where('min_power', '>=', $power)
            ->where('max_power', '<=', $power)
            ->first();
        return $chargeDetail;
    }


    public function getStatusDes()
    {
        return Arr::get(self::STATUS_MAP, $this->status);
    }


    public function getPaymentTypeDes()
    {
        return Arr::get(self::$paymentTypeMap, $this->payment_type);
    }


    public function scopeInUsing($query)
    {
        return $query->where('status', self::STATUS_USING);
    }


    //作用域 - 有效的


    /**
     * @return string
     */
    public static function getDistributorRelatePivotTable()
    {
        return 'distributor_orders';
    }

    /**
     * @return array
     */
    public static function getDistributorRelatePivotColumns()
    {
        return ['profit'];
    }



}
